package com.training.schedule_management_system_admin.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /*
    创建Realm对象
     */
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    /*
    DefaultWebSecurityManager
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        //关联自定义的Realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /*
    ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        bean.setLoginUrl("/noLogin");//未认证时跳转到指定页面
        bean.setUnauthorizedUrl("/noauth");//未授权时跳转到指定页面
        //添加shiro的内置过滤器
        Map<String,String> filterMap=new LinkedHashMap<>();
        /*
            anon:无需认证就可以访问
            authc:必须认证了才能访问
            user:必须拥有“记住我”功能才能使用
            perms:拥有对某个资源的权限才能访问
            roles:拥有某个角色权限才能访问
         */
//        filterMap.put("/toLogin","anon");
//        filterMap.put("/user/**")
        filterMap.put("/js/**","anon");
        filterMap.put("/css/**","anon");
        filterMap.put("/scss/**","anon");
        filterMap.put("/vendor/**","anon");
        filterMap.put("/imag","anon");

        filterMap.put("/reset-password","anon");
        filterMap.put("/login","anon");
        filterMap.put("/toLogin","anon");
        filterMap.put("/email","anon");
        filterMap.put("/register","anon");
        filterMap.put("/toRegister","anon");
        filterMap.put("/loginAction","anon");
        filterMap.put("/registerAction","anon");
        filterMap.put("/error/**","anon");

        filterMap.put("/scheduletable/**","authc");
        filterMap.put("/scheduletemplate/**","authc");
        filterMap.put("/share/**","authc");
        filterMap.put("/user/**","authc");
        filterMap.put("/logout","authc");
        filterMap.put("/admin/**","roles[admin]");

        bean.setFilterChainDefinitionMap(filterMap);
        return bean;
    }

    //整合ShiroDialect：用来将shiro和Thymeleaf整合
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
